package com.fansl.allround.oss.service;

import com.aliyun.oss.HttpMethod;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import com.fansl.allround.oss.api.config.AliYunOssPropertiesConfig;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Date;

/**
 * @author fansl
 * @Description: 阿里云服务
 * @date 2019/9/2 17:24
 */
@Slf4j
@Service
@AllArgsConstructor
public class AliyunOssService {
    private final AliYunOssPropertiesConfig aliYunOssPropertiesConfig;

    /**
     * 获取上传文件的签名url
     * @param objectName 文件名
     * @return
     */
    public URL getSignatureUrl(String objectName) {
        String bucketName = aliYunOssPropertiesConfig.getBucketName();
        OSS ossClient = getOssClient();

        // 生成签名URL
        long expirationTime = System.currentTimeMillis()+aliYunOssPropertiesConfig.getExpireInSeconds()*1000;
        Date expiration = new Date(expirationTime);
        GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucketName,objectName,HttpMethod.PUT);
        //设置过期时间
        request.setExpiration(expiration);
        // 设置Content-Type。
        request.setContentType("application/octet-stream");
        // 添加用户自定义元信息。
        request.addUserMetadata("author", "fansl");
        // 生成签名URL（HTTP PUT请求）。
        URL signedUrl = ossClient.generatePresignedUrl(request);
        log.info("signed url for putObject: " + signedUrl);

        return signedUrl;
    }

    /**
     * 创建OSSClient实例。
     * @return
     */
    public OSS getOssClient(){
        String endpoint = aliYunOssPropertiesConfig.getEndpoint();
        String accessKey = aliYunOssPropertiesConfig.getAccessKeyId();
        String secretKey = aliYunOssPropertiesConfig.getAccessKeySecret();
        OSS ossClient = new OSSClient(endpoint,accessKey,secretKey);
        return ossClient;
    }

    /**
     * 上传文件
     * @param file
     * @return
     */
    public Boolean uploadFile(MultipartFile file) {
        try {
            File file1 = file.getResource().getFile();
            if(file1.exists()){
                String key = file1.getName();

            }
        } catch (IOException e) {
            log.error("上传文件异常",e);
            throw new RuntimeException("上传文件异常");
        }
        return false;
    }
}
